import 'package:get/get.dart';
import 'package:raze/lore/glyph/community_essence.dart';
import 'package:raze/lore/glyph/community_comment_essence.dart';
import 'package:raze/lore/glyph/community_like_essence.dart';

/// 社区状态管理
/// 全局社区状态，提供社区发布、评论、点赞等功能
class CommunityChronicle extends GetxController {
  // 所有社区帖子列表
  final _communityList = <CommunityEssence>[].obs;

  // 所有评论列表
  final _commentList = <CommunityCommentEssence>[].obs;

  // 所有点赞记录列表
  final _likeList = <CommunityLikeEssence>[].obs;

  /// 获取所有社区帖子列表
  List<CommunityEssence> get communityList => _communityList;

  /// 获取所有评论列表
  List<CommunityCommentEssence> get commentList => _commentList;

  @override
  void onInit() {
    super.onInit();
    _initializeDefaultCommunities();
  }

  /// 初始化默认社区数据
  void _initializeDefaultCommunities() {
    final now = DateTime.now();

    // 初始化社区帖子（8条，其中2条视频）
    _communityList.value = [
      // 图片类型
      CommunityEssence(
        id: '1',
        userId: '1',
        contentType: 'image',
        media: 'assets/images/community1.png',
        detail:
            'Watching the plants stretch out gently after the rain, I suddenly feel that humans should also learn to slow down their breathing.',
        likeCount: 12,
        createTime: now.subtract(const Duration(days: 6)),
      ),
      CommunityEssence(
        id: '2',
        userId: '2',
        contentType: 'image',
        media: 'assets/images/community2.png',
        detail:
            'Today’s luck might just be this little green miracle glistening in the rain.Caught this beautiful moment - raindrops perfectly balanced on the leaf edges.',
        likeCount: 18,
        createTime: now.subtract(const Duration(days: 5, hours: 10)),
      ),
      // 视频类型
      CommunityEssence(
        id: '3',
        userId: '3',
        contentType: 'image',
        media: 'assets/images/community3.png',
        detail:
            'The moss has grown a little taller today. Maybe it doesn’t need the noise of sunlight—just a quiet rainfall.',
        likeCount: 25,
        createTime: now.subtract(const Duration(days: 4, hours: 8)),
      ),
      CommunityEssence(
        id: '4',
        userId: '1',
        contentType: 'image',
        media: 'assets/images/community4.png',
        detail:
            'A cluster of tiny new mushrooms has sprouted in the corner. They look like creatures that just popped out of a dream.',
        likeCount: 15,
        createTime: now.subtract(const Duration(days: 3, hours: 15)),
      ),
      CommunityEssence(
        id: '5',
        userId: '4',
        contentType: 'image',
        media: 'assets/images/community5.png',
        detail:
            'I go for a walk every time it rains. Not to just walk around, but simply to breathe alongside the plants.',
        likeCount: 9,
        createTime: now.subtract(const Duration(days: 2, hours: 20)),
      ),
      // 视频类型
      CommunityEssence(
        id: '6',
        userId: '1',
        contentType: 'video',
        media: 'assets/videos/video1.mp4',
        coverImage: 'assets/images/video1.jpg',
        detail:
            'Time-lapse of a plant drinking rainwater. So mesmerizing to watch!',
        likeCount: 32,
        createTime: now.subtract(const Duration(days: 2, hours: 5)),
      ),
    ];

    // 初始化点赞记录
    _likeList.value = [
      // 社区1的点赞（12个赞）
      CommunityLikeEssence(userId: '1', communityId: '1'),
      CommunityLikeEssence(userId: '2', communityId: '1'),
      CommunityLikeEssence(userId: '3', communityId: '1'),
      CommunityLikeEssence(userId: '4', communityId: '1'),
      CommunityLikeEssence(userId: '5', communityId: '1'),
      CommunityLikeEssence(userId: '6', communityId: '1'),
      CommunityLikeEssence(userId: '7', communityId: '1'),
      CommunityLikeEssence(userId: '8', communityId: '1'),
      CommunityLikeEssence(userId: '9', communityId: '1'),
      CommunityLikeEssence(userId: '10', communityId: '1'),
      CommunityLikeEssence(userId: '2', communityId: '1'),
      CommunityLikeEssence(userId: '3', communityId: '1'),
      // 社区2的点赞（18个赞）
      CommunityLikeEssence(userId: '1', communityId: '2'),
      CommunityLikeEssence(userId: '3', communityId: '2'),
      CommunityLikeEssence(userId: '4', communityId: '2'),
      CommunityLikeEssence(userId: '5', communityId: '2'),
      CommunityLikeEssence(userId: '6', communityId: '2'),
      CommunityLikeEssence(userId: '7', communityId: '2'),
      CommunityLikeEssence(userId: '8', communityId: '2'),
      CommunityLikeEssence(userId: '9', communityId: '2'),
      CommunityLikeEssence(userId: '10', communityId: '2'),
      // 社区3的点赞（25个赞）- 视频类型
      CommunityLikeEssence(userId: '1', communityId: '3'),
      CommunityLikeEssence(userId: '2', communityId: '3'),
      CommunityLikeEssence(userId: '4', communityId: '3'),
      CommunityLikeEssence(userId: '5', communityId: '3'),
      CommunityLikeEssence(userId: '6', communityId: '3'),
      CommunityLikeEssence(userId: '7', communityId: '3'),
      CommunityLikeEssence(userId: '8', communityId: '3'),
      CommunityLikeEssence(userId: '9', communityId: '3'),
      CommunityLikeEssence(userId: '10', communityId: '3'),
      // 社区4的点赞（15个赞）
      CommunityLikeEssence(userId: '2', communityId: '4'),
      CommunityLikeEssence(userId: '3', communityId: '4'),
      CommunityLikeEssence(userId: '4', communityId: '4'),
      CommunityLikeEssence(userId: '5', communityId: '4'),
      CommunityLikeEssence(userId: '6', communityId: '4'),
      CommunityLikeEssence(userId: '7', communityId: '4'),
      CommunityLikeEssence(userId: '8', communityId: '4'),
      CommunityLikeEssence(userId: '9', communityId: '4'),
      CommunityLikeEssence(userId: '10', communityId: '4'),
      // 社区5的点赞（9个赞）
      CommunityLikeEssence(userId: '1', communityId: '5'),
      CommunityLikeEssence(userId: '2', communityId: '5'),
      CommunityLikeEssence(userId: '3', communityId: '5'),
      CommunityLikeEssence(userId: '6', communityId: '5'),
      CommunityLikeEssence(userId: '7', communityId: '5'),
      CommunityLikeEssence(userId: '8', communityId: '5'),
      CommunityLikeEssence(userId: '9', communityId: '5'),
      CommunityLikeEssence(userId: '10', communityId: '5'),
      // 社区6的点赞（32个赞）- 视频类型
      CommunityLikeEssence(userId: '1', communityId: '6'),
      CommunityLikeEssence(userId: '2', communityId: '6'),
      CommunityLikeEssence(userId: '3', communityId: '6'),
      CommunityLikeEssence(userId: '4', communityId: '6'),
      CommunityLikeEssence(userId: '7', communityId: '6'),
      CommunityLikeEssence(userId: '8', communityId: '6'),
      CommunityLikeEssence(userId: '9', communityId: '6'),
      CommunityLikeEssence(userId: '10', communityId: '6'),
      // 社区7的点赞（14个赞）
      CommunityLikeEssence(userId: '1', communityId: '7'),
      CommunityLikeEssence(userId: '2', communityId: '7'),
      CommunityLikeEssence(userId: '3', communityId: '7'),
      CommunityLikeEssence(userId: '4', communityId: '7'),
      CommunityLikeEssence(userId: '5', communityId: '7'),
      CommunityLikeEssence(userId: '8', communityId: '7'),
      CommunityLikeEssence(userId: '9', communityId: '7'),
      CommunityLikeEssence(userId: '10', communityId: '7'),
      // 社区8的点赞（11个赞）
      CommunityLikeEssence(userId: '1', communityId: '8'),
      CommunityLikeEssence(userId: '2', communityId: '8'),
      CommunityLikeEssence(userId: '3', communityId: '8'),
      CommunityLikeEssence(userId: '4', communityId: '8'),
      CommunityLikeEssence(userId: '5', communityId: '8'),
      CommunityLikeEssence(userId: '6', communityId: '8'),
      CommunityLikeEssence(userId: '9', communityId: '8'),
      CommunityLikeEssence(userId: '10', communityId: '8'),
    ];

    // 初始化评论
    _commentList.value = [
      // 社区1的评论
      CommunityCommentEssence(
        id: '1',
        communityId: '1',
        userId: '2',
        content: 'Your garden looks amazing! Rain really does wonders.',
        createTime: now.subtract(const Duration(days: 6, hours: -2)),
      ),
      CommunityCommentEssence(
        id: '2',
        communityId: '1',
        userId: '3',
        content: 'I can see the difference already! So vibrant!',
        createTime: now.subtract(const Duration(days: 5, hours: 20)),
      ),
      // 社区2的评论
      CommunityCommentEssence(
        id: '3',
        communityId: '2',
        userId: '1',
        content:
            'What a beautiful capture! The droplets are perfectly balanced.',
        createTime: now.subtract(const Duration(days: 5, hours: 8)),
      ),
      CommunityCommentEssence(
        id: '4',
        communityId: '2',
        userId: '4',
        content: 'This is photography at its finest!',
        createTime: now.subtract(const Duration(days: 4, hours: 18)),
      ),
      // 社区3的评论（视频）
      CommunityCommentEssence(
        id: '5',
        communityId: '3',
        userId: '1',
        content: 'This video is so educational! Thank you for sharing.',
        createTime: now.subtract(const Duration(days: 4, hours: 6)),
      ),
      CommunityCommentEssence(
        id: '6',
        communityId: '3',
        userId: '5',
        content: 'I watched this three times! Mesénmerizing!',
        createTime: now.subtract(const Duration(days: 3, hours: 22)),
      ),
      // 社区4的评论
      CommunityCommentEssence(
        id: '7',
        communityId: '4',
        userId: '2',
        content: 'Nature truly is an artist!',
        createTime: now.subtract(const Duration(days: 3, hours: 12)),
      ),
      // 社区5的评论
      CommunityCommentEssence(
        id: '8',
        communityId: '5',
        userId: '1',
        content: 'I love watching plants in the rain!',
        createTime: now.subtract(const Duration(days: 2, hours: 18)),
      ),
      // 社区6的评论（视频）
      CommunityCommentEssence(
        id: '9',
        communityId: '6',
        userId: '1',
        content: 'Time-lapse videos are my favorite! Great work!',
        createTime: now.subtract(const Duration(days: 2, hours: 3)),
      ),
      CommunityCommentEssence(
        id: '10',
        communityId: '6',
        userId: '3',
        content: 'This is incredible! How long did it take?',
        createTime: now.subtract(const Duration(days: 1, hours: 18)),
      ),
      // 社区7的评论
      CommunityCommentEssence(
        id: '11',
        communityId: '7',
        userId: '4',
        content: 'The morning after rain is always the best time!',
        createTime: now.subtract(const Duration(days: 1, hours: 10)),
      ),
      // 社区8的评论
      CommunityCommentEssence(
        id: '12',
        communityId: '8',
        userId: '5',
        content: 'Each pattern is unique! Nature never ceases to amaze.',
        createTime: now.subtract(const Duration(hours: 6)),
      ),
    ];
  }

  /// 发布社区帖子
  /// [userId] 发布者用户ID
  /// [contentType] 内容类型：'image' 或 'video'
  /// [media] 媒体路径
  /// [coverImage] 视频封面图（仅视频类型需要）
  /// [detail] 详情文字
  /// 返回创建的社区帖子ID
  String publishCommunity({
    required String userId,
    required String contentType,
    required String media,
    String? coverImage,
    required String detail,
  }) {
    final newId = (_communityList.length + 1).toString();
    final newCommunity = CommunityEssence(
      id: newId,
      userId: userId,
      contentType: contentType,
      media: media,
      coverImage: coverImage,
      detail: detail,
      likeCount: 0,
      createTime: DateTime.now(),
    );
    _communityList.add(newCommunity);
    return newId;
  }

  /// 对社区帖子点赞
  /// [userId] 点赞用户ID
  /// [communityId] 社区帖子ID
  /// 返回操作结果，成功返回true，失败返回false（已点赞或帖子不存在）
  bool likeCommunity(String userId, String communityId) {
    // 检查是否已点赞
    final hasLiked = _likeList.any(
      (like) => like.userId == userId && like.communityId == communityId,
    );

    if (hasLiked) {
      return false; // 已点赞
    }

    final index = _communityList.indexWhere((c) => c.id == communityId);
    if (index == -1) {
      return false; // 帖子不存在
    }

    // 添加点赞记录
    _likeList.add(
      CommunityLikeEssence(userId: userId, communityId: communityId),
    );

    // 更新点赞数
    final community = _communityList[index];
    _communityList[index] = community.copyWith(
      likeCount: community.likeCount + 1,
    );
    return true;
  }

  /// 取消点赞
  /// [userId] 用户ID
  /// [communityId] 社区帖子ID
  /// 返回操作结果，成功返回true，失败返回false（未点赞）
  bool unlikeCommunity(String userId, String communityId) {
    final likeIndex = _likeList.indexWhere(
      (like) => like.userId == userId && like.communityId == communityId,
    );

    if (likeIndex == -1) {
      return false; // 未点赞
    }

    _likeList.removeAt(likeIndex);

    // 更新点赞数
    final index = _communityList.indexWhere((c) => c.id == communityId);
    if (index != -1) {
      final community = _communityList[index];
      _communityList[index] = community.copyWith(
        likeCount: community.likeCount - 1,
      );
    }

    return true;
  }

  /// 检查用户是否已对社区帖子点赞
  /// [userId] 用户ID
  /// [communityId] 社区帖子ID
  /// 返回是否已点赞
  bool checkCommunityLiked(String userId, String communityId) {
    return _likeList.any(
      (like) => like.userId == userId && like.communityId == communityId,
    );
  }

  /// 发表评论
  /// [communityId] 社区帖子ID
  /// [userId] 评论者用户ID
  /// [content] 评论内容
  /// 返回创建的评论ID
  String postComment(String communityId, String userId, String content) {
    final newId = (_commentList.length + 1).toString();
    final newComment = CommunityCommentEssence(
      id: newId,
      communityId: communityId,
      userId: userId,
      content: content,
      createTime: DateTime.now(),
    );
    _commentList.add(newComment);
    return newId;
  }

  /// 获取社区帖子的所有评论列表
  /// [communityId] 社区帖子ID
  /// 返回按时间排序的该帖子的所有评论列表
  List<CommunityCommentEssence> fetchComments(String communityId) {
    return _commentList
        .where((comment) => comment.communityId == communityId)
        .toList()
      ..sort((a, b) => a.createTime.compareTo(b.createTime));
  }

  /// 根据ID查询社区帖子
  /// [communityId] 社区帖子ID
  /// 返回社区帖子，不存在返回null
  CommunityEssence? queryCommunityById(String communityId) {
    return _communityList.firstWhereOrNull((c) => c.id == communityId);
  }

  /// 删除社区帖子
  /// [communityId] 社区帖子ID
  /// 返回操作结果，成功返回true，失败返回false（帖子不存在）
  bool deleteCommunityById(String communityId) {
    final index = _communityList.indexWhere((c) => c.id == communityId);
    if (index == -1) {
      return false; // 帖子不存在
    }

    // 删除社区帖子
    _communityList.removeAt(index);

    // 删除该帖子的所有评论
    _commentList.removeWhere((comment) => comment.communityId == communityId);

    // 删除该帖子的所有点赞记录
    _likeList.removeWhere((like) => like.communityId == communityId);

    return true;
  }

  /// 删除评论
  /// [commentId] 评论ID
  /// 返回操作结果，成功返回true，失败返回false（评论不存在）
  bool eraseCommentById(String commentId) {
    final index = _commentList.indexWhere((comment) => comment.id == commentId);
    if (index == -1) {
      return false; // 评论不存在
    }

    // 删除评论
    _commentList.removeAt(index);

    return true;
  }
}
